//
//  LGEditPersonalDataController.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/2/14.
//  编辑个人资料

#import "LGEditPersonalDataController.h"
#import "LGLineTitleTipView.h"
#import "LGPersonalInputView.h"
#import "LGPickerView.h"
#import <ImSDK_Plus/V2TIMManager.h>
@interface LGEditPersonalDataController ()<LGPersonalInputDelegate,LGPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
/**   */
@property (nonatomic , strong)UIScrollView *scrollView;
/**   */
@property (nonatomic , strong)UIView *infoView;
/**   */
@property (nonatomic , strong)LGLineTitleTipView *headView;
/**   */
@property (nonatomic , strong)LGLineTitleTipView *postitleView;
/**   */
@property (nonatomic , strong)UILabel *introduceTitle;
/**   */
@property (nonatomic , strong)LGPersonalInputView *introduceView;
/**   */
@property (nonatomic , strong)UILabel *goodTitle;
/**   */
@property (nonatomic , strong)LGPersonalInputView *goodView;
/**   */
@property (nonatomic , strong)UIButton *saveBtn;
/**   */
@property (nonatomic , strong)NSArray *jobArray;

@end

@implementation LGEditPersonalDataController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createSubView];
    [self requestData];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/dict/option/code/profess" parameters:@{} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        if(code == 200){
            self.jobArray = returnData;
        }
    } error:^(NSError *error) {
        
    }];
}

-(void)setInfoDic:(NSDictionary *)infoDic{
    _infoDic = infoDic;
    self.headView.content = infoDic[@"avatar_url"];
    [self.headView.imageView sd_setImageWithURL:[NSURL URLWithString:infoDic[@"avatar_url"]] placeholderImage:defaultDoctorPic];
    self.postitleView.content = infoDic[@"profess"];
    self.introduceView.content = infoDic[@"intro"];
    self.goodView.content = infoDic[@"adeptat"];
}

//保存个人资料
-(void)saveBtnAction{
    if(self.headView.content.length == 0){
        [TooltipView showMessage:@"请上传头像" offset:0];
    }else if (self.postitleView.content.length == 0){
        [TooltipView showMessage:@"请选择职称" offset:0];
    }else{
        NSString *intro = [self.introduceView.contentTF.text isEqualToString:self.introduceView.placeHolder]?@"":self.introduceView.contentTF.text;
        NSString *adeptat = [self.goodView.contentTF.text isEqualToString:self.goodView.placeHolder]?@"":self.goodView.contentTF.text;
        
        NSString *job = @"";
        for (NSDictionary *tempDic in self.jobArray) {
            if([self.postitleView.content isEqualToString:tempDic[@"title"]]){
                job = LGNSString(tempDic[@"value"]);
            }
        }
        [RequestUtil withPOST:@"/doctor/my.profile/save" parameters:@{@"avatar":self.headView.content,@"profess":job,@"intro":intro,@"adeptat":adeptat} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                [self.navigationController popViewControllerAnimated:YES];
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } error:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }];
    }
}

-(void)infoViewTapAction:(UITapGestureRecognizer *)sender{
    CGPoint point = [sender locationInView:self.infoView];
    if(point.y>viewPix(67)){
        //选择职称
        if(self.jobArray.count == 0){
            [self requestData];
        }else{
            NSMutableArray *tempArray = [NSMutableArray array];
            for (NSDictionary *tempDic in self.jobArray) {
                [tempArray addObject:LGNSString(tempDic[@"title"])];
            }
            LGPickerView *pickerView = [[LGPickerView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H)];
            pickerView.pickArry = @[tempArray];
            pickerView.selectStr = self.postitleView.content;
            pickerView.delegate = self;
            [self.view.window addSubview:pickerView];
        }
    }else{
        //更换头像
        [self selectHeadPic];
    }
}

-(void)selectPickerViewResult:(NSArray *)resultArray{
    self.postitleView.content = LGNSString(resultArray[0]);
}



#pragma mark---相机、相册代理方法
-(void)selectHeadPic{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册选择图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *pickController = [[UIImagePickerController alloc]init];
            pickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickController.delegate = self;
            pickController.allowsEditing = YES;
            pickController.modalPresentationStyle = UIModalPresentationFullScreen;
            pickController.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:pickController animated:YES completion:nil];
        }
    }];
    
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *pickController = [[UIImagePickerController alloc]init];
            pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            pickController.delegate = self;
            pickController.allowsEditing = YES;
            pickController.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:pickController animated:YES completion:nil];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:photoAction];
    [alertController addAction:cameraAction];
    [alertController addAction:cancelAction];
    if (isPad) {
        alertController.popoverPresentationController.sourceView = self.view;
        alertController.popoverPresentationController.sourceRect = CGRectMake(0, Screen_H, Screen_W, viewPix(300));
    }
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    UIImage *myImage = info[@"UIImagePickerControllerEditedImage"];
    [picker dismissViewControllerAnimated:YES completion:^{
        [RequestUtil uploadImage:@"/doctor/upload/avatar" parameters:@{} withSign:YES indexName:@"photo" imageArray:@[myImage] success:^(NSInteger code, NSString *message, id returnData) {
            if(code == 200){
                self.headView.imageView.image = myImage;
                self.headView.content = returnData[@"uri"];
                __block NSString *faceUrl = LGNSString(returnData[@"url"]);
                NSString *loginUser = [[V2TIMManager sharedInstance] getLoginUser];
                [[V2TIMManager sharedInstance] getUsersInfo:@[loginUser] succ:^(NSArray<V2TIMUserFullInfo *> *infoList) {
                    if (infoList.firstObject) {
                        V2TIMUserFullInfo *userInfo = infoList.firstObject;
                        userInfo.faceURL = faceUrl;
                        [[V2TIMManager sharedInstance] setSelfInfo:userInfo succ:nil fail:nil];
                    }
                } fail:nil];
              
            }else{
                [TooltipView showMessage:message offset:0];
            }
        } failure:^(NSError *error) {
            [TooltipView showMessage:LGErrorMessage offset:0];
        }]; 
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


//输入框高度变化
-(void)inputContentChanged:(CGFloat)height viewTag:(NSInteger)tag{
    LGPersonalInputView *inputView = [self.view viewWithTag:tag];
    [inputView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@(height+viewPix(55)));
        self.scrollView.contentSize = CGSizeMake(Screen_W, kMaxY(self.saveBtn.frame)+viewPix(50));
    }];
    [self performSelector:@selector(resetContentSize) withObject:nil afterDelay:0.5];
}

-(void)resetContentSize{
    self.scrollView.contentSize = CGSizeMake(Screen_W, kMaxY(self.saveBtn.frame)+viewPix(50));
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.title = @"编辑个人资料";
    [self.view addSubview:self.scrollView];
    [self.scrollView addSubview:self.infoView];
    [self.infoView addSubview:self.headView];
    [self.infoView addSubview:self.postitleView];
    [self.scrollView addSubview:self.introduceTitle];
    [self.scrollView addSubview:self.introduceView];
    [self.scrollView addSubview:self.goodTitle];
    [self.scrollView addSubview:self.goodView];
    [self.scrollView addSubview:self.saveBtn];
    [self.introduceView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.introduceTitle.mas_bottom).offset(viewPix(12));
        make.left.equalTo(self.view).offset(viewPix(16));
        make.right.equalTo(self.view).offset(-viewPix(16));
        make.height.equalTo(@(viewPix(105)));
    }];
    [self.goodTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.introduceView.mas_bottom).offset(viewPix(21));
        make.left.right.equalTo(self.introduceView);
    }];
    [self.goodView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.goodTitle.mas_bottom).offset(viewPix(7));
        make.left.right.equalTo(self.introduceView);
        make.height.equalTo(@(viewPix(105)));
    }];
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.goodView.mas_bottom).offset(viewPix(28));
        make.left.right.equalTo(self.introduceView);
        make.height.equalTo(@(viewPix(48)));
    }];
}
-(UIScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight)];
        _scrollView.backgroundColor = [UIColor colorWithString:@"#F9F9F9"];
        _scrollView.contentSize = CGSizeMake(Screen_W, Screen_H-topBarHeight+2);
    }
    return _scrollView;
}

-(UIView *)infoView{
    if(!_infoView){
        _infoView = [[UIView alloc] initWithFrame:CGRectMake(viewPix(16), viewPix(16), Screen_W-viewPix(32), viewPix(116))];
        [_infoView setShadoWithColor:@"#B2BDC7" offset:CGSizeMake(0, 2) opacity:0.15 radius:15];
        _infoView.backgroundColor = [UIColor whiteColor];
        [_infoView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(infoViewTapAction:)]];
    }
    return _infoView;
}

-(LGLineTitleTipView *)headView{
    if(!_headView){
        _headView = [[LGLineTitleTipView alloc] initWithFrame:CGRectMake(0, 0, Screen_W-viewPix(32), viewPix(68))];
        _headView.type = @"image";
        _headView.title = @"头像";
    }
    return _headView;
}

-(LGLineTitleTipView *)postitleView{
    if(!_postitleView){
        _postitleView = [[LGLineTitleTipView alloc] initWithFrame:CGRectMake(0, viewPix(68), Screen_W-viewPix(32), viewPix(48))];
        _postitleView.lineView.hidden = YES;
        _postitleView.type = @"text";
        _postitleView.title = @"职称";
    }
    return _postitleView;
}

-(UILabel *)introduceTitle{
    if(!_introduceTitle){
        _introduceTitle = [UILabel lableWithText:@"个人简介" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _introduceTitle.frame = CGRectMake(viewPix(16), kMaxY(self.infoView.frame)+viewPix(16), Screen_W-viewPix(32), viewPix(23));
    }
    return _introduceTitle;
}


-(LGPersonalInputView *)introduceView{
    if(!_introduceView){
        _introduceView = [[LGPersonalInputView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.introduceTitle.frame)+viewPix(16), Screen_W-viewPix(32), viewPix(105))];
        [_introduceView setShadoWithColor:@"#B3C5D9" offset:CGSizeMake(0, 2) opacity:0.15 radius:15];
        _introduceView.backgroundColor = [UIColor whiteColor];
        _introduceView.delegate = self;
        _introduceView.tag = 1000;
    }
    return _introduceView;
}


-(UILabel *)goodTitle{
    if(!_goodTitle){
        _goodTitle = [UILabel lableWithText:@"擅长领域" colorString:@"#333333" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:1];
        _goodTitle.frame = CGRectMake(viewPix(16), kMaxY(self.introduceView.frame)+viewPix(16), Screen_W-viewPix(32), viewPix(23));
    }
    return _goodTitle;
}


-(LGPersonalInputView *)goodView{
    if(!_goodView){
        _goodView = [[LGPersonalInputView alloc] initWithFrame:CGRectMake(viewPix(16), kMaxY(self.goodTitle.frame)+viewPix(16), Screen_W-viewPix(32), viewPix(105))];
        [_goodView setShadoWithColor:@"#B3C5D9" offset:CGSizeMake(0, 2) opacity:0.15 radius:15];
        _goodView.backgroundColor = [UIColor whiteColor];
        _goodView.delegate = self;
        _goodView.tag = 1001;
    }
    return _goodView;
}


-(UIButton *)saveBtn{
    if(!_saveBtn){
        _saveBtn = [UIButton buttonWithTitle:@"保存" titleFont:LGFontWeight(16, UIFontWeightMedium) textColor:@"#FFFFFF" imageName:@""];
        _saveBtn.backgroundColor = [UIColor colorWithString:@"#429BFF"];
        _saveBtn.cornerRidus = 10;
        [_saveBtn addTarget:self action:@selector(saveBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
